#-*- coding: utf-8 -*-
#! /usr/bin/python
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
import sys
#import time
import ConfigParser

reload(sys)
sys.setdefaultencoding("utf-8")

def initConfig(filename):
    '''
    去掉文件头BOM等
    Window下用记事本打开配置文件并修改保存后，编码为UNICODE
    或UTF-8的文件的文件头
    #会被相应的加上\xff\xfe（\xff\xfe）或\xef\xbb\xbf
    '''
    import re
    content = open(filename).read()
    content = re.sub(r"\xfe\xff", "", content)
    content = re.sub(r"\xff\xfe", "", content)
    content = re.sub(r"\xef\xbb\xbf", "", content)
    open(filename, 'w').write(content)


def loginAlipay(aliname, alipass):
    '''
    aliname一般是一个email
    login alipay
    '''
    chrome.delete_all_cookies()
    lgurl = 'https://auth.alipay.com/login/index.htm?goto=https%3A%2F%2Flab.alipay.com%2Fuser%2Fi.htm'
    chrome.get(lgurl)
    #set username password
    try:
        txtname = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_name("logonId"))
        chrome.execute_script("document.getElementById('logonId').value = ''")
        txtname.send_keys(aliname)
        textname.click()        
    except:
        print 'fail to get element logonId'
    keybd(9)#tab
    try:
        #pwspan = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("password_container"))
        #pwspan.click()
        #pwbox.send_keys(alipass)
        typeme(alipass)
    except:
        print 'fail to get type password'
    try:
        sbtn = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_name("submit_btn"))
        sbtn.submit()
    except:
        print 'fail to get element submit_btn'
    
    
    def ordd(str):
        '''
        解决键盘码不对应问题,不知道别的电脑有没有这个问题
        '''
        t = ord(str)
        #65到90是A到Z
        if(t>90):
            return t-32
        else:
            #print t
            return t
    
    
    def typeme(passw):
        '''
        模拟人工输入,自动输入参数字符串到焦点窗口
        '''
        psht = len(passw)
        for j in range(psht):
            win32api.keybd_event(ordd(passw[j]), 0, 0, 0)
            time.sleep(0.5)
            win32api.keybd_event(ordd(passw[j]), 0, win32con.KEYEVENTF_KEYUP, 0)
            time.sleep(0.5)
    
    
    def keybd(keynum):
        win32api.keybd_event(keynum, 0, 0, 0)
        time.sleep(0.5)
        win32api.keybd_event(keynum, 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(0.5)
        
    

def qr(username, ppass):
    '''
    queren shouhuo
    '''
    try:#show list
        needtoconfirm = chrome.find_elements_by_class_name('to-sure')
        needtoconfirm[0].click()
    except:
        print 'fail to get element qrlist'
    try:#selectall
        for handle in chrome.window_handles:
            chrome.switch_to_window(handle)
            print chrome.title.decode('utf-8')
            if(chrome.title == '已买到的宝贝'.decode('utf-8')):
                break
        allbox = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("J_AllSelector"))
        allbox.click()
    except:
        print 'fail to get element allcheck'
    try:#batch sure
        #ybtn =  WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_link_text('在该网站上始终运行').decode('utf-8')))
        #ybtn.click()
        bbt = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("J_BatchReceive"))
        bbt.click()
    except:
        print 'fail to get element J_BatchReceive'
    try:#sure
        for handle in chrome.window_handles:
            chrome.switch_to_window(handle)
            print (chrome.title).decode('utf-8')
            if(chrome.title == '确认收货'.decode('utf-8')):
                break
        chrome.switch_to_frame("alipay-iframe")
        chrome.execute_script("document.getElementById('password').value = "+ppass)
        sfm = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("authorizeOnceForm"))
        sfm.submit()
    except:
        print 'fail to get element authorizeOnceForm'

    
def mainfun():
    config = ConfigParser.ConfigParser()
    initConfig('fast.ini')
    config.read('fast.ini')
    xiaohaocount = int(config.get("global", "xiaohaocount"))
    xiaohao = range(xiaohaocount)
    lpass = range(xiaohaocount)
    ppass = range(xiaohaocount)
    for i in range(xiaohaocount):
        xiaohao[i] = config.get("xiaohao", "hao"+str(i+1))    
        lpass[i] = config.get("lpass", "lpass"+str(i+1))    
        ppass[i] = config.get("ppass", "ppass"+str(i+1))
        if(loginTb(xiaohao[i], lpass[i])):
            try:
                qr(xiaohao[i], ppass[i])    
                print 'sure it'
                #logoutTb()
            except:
                print 'QR Error!!'


def daifu(aliname, alipass):
    '''
    拍下后选择代付款,用指定代付账号
    记录下代付款链接
    '''

chrome = webdriver.Chrome()
#chrome.switch_to_active_element
aliname = 'yanyu2008@sogou.com'
alipass = 'jhf178#@'

#loginAlipay(aliname, alipass)

mainfun()

